var Wish = mongoose.model('wish');
var UserWish = mongoose.model('user_wish');

var WISH_STATUS = {1: '征集支持中', 2: '实现中', 3: '愿望失败', 4: '已实现'};
var WISH_TYPE = {1: "普通", 2: "精选"};

function validateUserWishStatus(userwish, callback) {
    var wishId = userwish._id;
    var status = userwish.status ? userwish.status : "";
    if (!userwish.status || !userwish.dateExpired || !userwish.wish || typeof userwish.wish != "object" || !userwish.wish.minSupport) {
        getUserWishFunc({_id: wishId}, function (err, result) {
            status = userwish.status;
            if (!err && result != null) {
                checkUserWishStatus(userwish);
            }
            if (status != userwish.status) {
                console.log("CHANGE IN WISH STATUS",wishId,status,"->>>",userwish.status);
                updateUserWishFunc({_id: wishId}, {'status': userwish.status}, callback);
            } else
                callback(err, userwish);
        })
    } else {
        checkUserWishStatus(userwish);
        if (status != userwish.status) {
            console.log("CHANGE IN WISH STATUS",wishId,status,"->>>",userwish.status);
            updateUserWishFunc({_id: wishId}, {'status': userwish.status}, callback);
        } else
            callback(null, userwish);
    }
}

function checkUserWishStatus(userwish) {
    var status = userwish.status;
    var expiryDate = new Date(userwish.dateExpired);
    var curDate = new Date();
    if (status != WISH_STATUS[1])
        return;
    if (userwish.wish && userwish.supporters.length > userwish.wish.minSupport) {
        userwish.status = WISH_STATUS[2];
    }
    else if (curDate > expiryDate) {
        userwish.status = WISH_STATUS[3];
    }
}

function addUserWishDetail(data, callback) {
    if (data.supporters)
        data.supportCount = data.supporters.length;
    if (data.status == WISH_STATUS[4] || data.status == WISH_STATUS[3])
        return;
    if (data.dateExpired) {
        var expiryDate = new Date(data.dateExpired);
        var curDate = new Date();
        if (expiryDate > curDate) {
            var timeLeft = (expiryDate - curDate) / (36e5 * 24);
            var daysLeft = Math.floor(timeLeft);
            var hoursLeft = (timeLeft - daysLeft) * 24;
            var minutesLeft = ((hoursLeft - Math.floor(hoursLeft)) * 60);
            var secondsLeft = ((minutesLeft - Math.floor(minutesLeft)) * 60);
            data.timeLeft = {
                days: daysLeft,
                hours: Math.floor(hoursLeft),
                minutes: Math.floor(minutesLeft),
                seconds: Math.floor(secondsLeft)
            }
        }
    }
    validateUserWishStatus(data, callback);
}

var wishPopulate = 'desc minSupport maxDays images';

function getWishFunc(query, callback) {
    Wish.findOne(query).exec(callback);
}

function getUserWishFunc(query, callback) {
    UserWish.findOne(query).populate('wish', wishPopulate).exec(function (err, result) {
        if (!err && result != null) {
            addUserWishDetail(result, function () {
            });
        }
        callback(err, result);
        updateUserWishFunc({_id:result._id}, {"$inc":{"browseCount":1}}, function(){});
    })
}

function getUserWishListFunc(query, callback) {
    UserWish.find(query).sort({_id:-1}).populate('wish', wishPopulate).exec(function (err, result) {
        if (!err && result != null) {
            var lenn = result.length;
            for (var i = 0; i < lenn; ++i) {
                addUserWishDetail(result[i], function () {
                });
            }
        }
        callback(err, result);
    })
}

function updateMongoObj (updateObj) {
    if (!updateObj.$set) {
        updateObj = {$set: updateObj};
    }
    updateObj.$set.dateLastModified = new Date();
}

function updateWishFunc(query, updateObj, callback) {
    updateMongoObj(updateObj);
    Wish.update(query, updateObj).exec(callback);
}

function updateUserWishFunc(query, updateObj, callback) {
    updateMongoObj(updateObj);
    UserWish.update(query, updateObj).exec(callback);
}

exports.Wish = Wish;
exports.UserWish = UserWish;
exports.WISH_STATUS = WISH_STATUS;
exports.WISH_TYPE = WISH_TYPE;

exports.getWishFunc = getWishFunc;
exports.updateWishFunc = updateWishFunc;

exports.validateUserWishStatus = validateUserWishStatus;
exports.checkUserWishStatus = checkUserWishStatus;
exports.addUserWishDetail = addUserWishDetail;

exports.getUserWishFunc = getUserWishFunc;
exports.getUserWishListFunc = getUserWishListFunc;
exports.updateUserWishFunc = updateUserWishFunc;

exports.randomWishAlgorithm = function(wishArray) {
    var sumOfWeights = 0;
    var cumulativeSumIdx = {};
    var lenn = wishArray.length;
    for(var i =0; i < lenn; ++i) {
        sumOfWeights += wishArray[i].weight;
        cumulativeSumIdx[i] = sumOfWeights;
    }
    var rndSum = Math.random() * sumOfWeights;
    var rndIdx = 0;
    for (var i in cumulativeSumIdx) {
        if (cumulativeSumIdx[i] > rndSum) {
            rndIdx = i;
            break;
        }
    }
    //console.log("RAND SUM", rndSum)
    //console.log("SUM WEIGHTS", sumOfWeights)
    //console.log("IDX", rndIdx, "DISCRETE SUM OF IDX", cumulativeSumIdx[rndIdx])
    //console.log(wishArray[rndIdx])
    return wishArray[rndIdx];
};